<?php
/**
 * 发起订单支付入口
 */
require_once(dirname(__FILE__)."/../include/common.inc.php");
require_once(DEDEINC.'/payment/xorpay.php');
require_once(DEDEDATA.'/payment/xorpay.php');
helper(array('xorpay','cache'));
header("content-type:text/html;charset=".$cfg_soft_lang);
$domain = strpos($cfg_phpurl,'http')===0 ? $cfg_phpurl : getLocalDomain().$cfg_phpurl;
$_POST = array_merge($_POST,$_GET);
extract($_POST);
if($payment['pay_subject']) $subject = $payment['pay_subject'];
if($_REQUEST['subject']) $subject = $_REQUEST['pay_subject'];
if(!$subject) $subject = '订单号：'.$out_trade_no;
$total_fee = $price ? $price/100 : $total_fee;
$openid = $openId ? $openId : $openid;
$qrUrl = $qrUrl ? $qrUrl : $domain.'/xorpay_pay.php?out_trade_no='.$out_trade_no.'&total_fee='.$total_fee;
if($action=='checkorder' && $out_trade_no){
    $data['code'] = 1;
    $status = GetCache('order',$out_trade_no);
    if($status!==false){
        $data['code'] = intval($status);
        echo json_encode($data);exit();
    }
    $sql = "SELECT * FROM `#@__xororder` WHERE `out_trade_no` = '{$out_trade_no}' order by id desc limit 1";
    $row = $dsql->GetOne($sql);
    if($row){
        $data['code'] = intval($row['status']);
        //设置缓存
        SetCache('order',$out_trade_no,$data['code']);
        echo json_encode($data);exit();
    }
    echo json_encode($data);exit();
}
if($action=='notify'){
    //error_log(print_r($_POST,true),3,'1.txt');
    $_GET['code'] = 'xorpay';
    $pay = new xorpay();
    $pay->respond();
    echo 'ok';exit();
}
if($action=='getQrcode'){
	$sql = "UPDATE `#@__xororder` SET `pay_type`='{$paymode}' WHERE `out_trade_no`='{$out_trade_no}' and status = 1";
	$dsql->ExecuteNoneQuery($sql);
    $payService = new XorpayService();
	$payService->setAid($payment['aid']);
	$payService->setKey($payment['appkey']);
	$payService->setTotalFee($total_fee);
	$payService->setNotifyUrl($payment['notify_url']);
	$payService->setOutTradeNo($out_trade_no);
	$payService->setBody($subject);
	$payService->setPayTip($payment['pay_tip']);
	$payService->setPayMode($paymode);
	echo $payService->getQrcode();exit();
}

if($action=='return'):
?>
    <!DOCTYPE html>
    <html lang="zh-cmn-Hans">
    <head>
        <meta charset="<?php echo $cfg_soft_lang; ?>">
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
        <title>支付成功</title>
        <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/1.1.3/weui.min.css"/>
        <style>
            @media (min-width: 768px) {.weui-msg__opr-area{width: 300px;margin:0 auto}}
        </style>
    </head>
    </head>
    <body>
    <div class="container" id="container">
        <div class="page msg_warn js_show">
            <div class="weui-msg">
                <div class="weui-msg__icon-area"><i class="weui-icon-success weui-icon_msg"></i></div>
                <div class="weui-msg__text-area">
                    <h2 class="weui-msg__title">支付成功</h2>
                    <p class="weui-msg__desc">订单号：<?php echo $out_trade_no;?></a></p>
                    <p class="weui-msg__desc">订单金额：<?php echo $total_fee;?>元</a></p>
                </div>
                <div class="weui-msg__opr-area">
                    <p class="weui-btn-area">
                        <?php
                        if(isWeixin()):
                            ?>
                            <a href="javascript:;" onclick="WeixinJSBridge.call('closeWindow');" class="weui-btn weui-btn_primary">关闭</a>
                        <?php
                        else:
                            ?>
                            <a href="<?php echo $cfg_basehost?>" class="weui-btn weui-btn_primary">返回网站</a>
                        <?php
                        endif;
                        ?>
                    </p>
                </div>
                <div class="weui-msg__extra-area">
                    <div class="weui-footer">
                        <p class="weui-footer__links">
                            <a href="javascript:void(0);" class="weui-footer__link"><?php echo $cfg_webname;?></a>
                        </p>
                        <p class="weui-footer__text"><?php echo $cfg_powerby;?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
<?php
	exit();
endif;
if($action=='jspay'):
	$payService = new XorpayService();
	$payService->setAid($payment['aid']);
	$payService->setKey($payment['appkey']);
	$payService->setTotalFee($totalFee);
	$payService->setNotifyUrl($payment['notify_url']);
	$payService->setOutTradeNo($outTradeNo);
	$payService->setBody($body);
	$payService->setPayTip($payment['pay_tip']);
	$payService->setOpenid($openid);
	$jsapi = $payService->getJsApiParameters();	
    if(!$jsapi || !is_array($jsapi)){
        ShowMsg('为获取到jsapi参数','javascript:;');
        exit;
	}	
?>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $cfg_soft_lang; ?>">
	<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="format-detection" content="telephone=no">
	<meta name="format-detection" content="email=no">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<link href="//res.wx.qq.com/open/libs/weui/1.1.3/weui.min.css" rel="stylesheet">
	<style>
		body{background-color:#f8f8f8;padding:0;margin:0;}
		.header {border-bottom: 1px solid #ccc;background-color: #fff;}
		.footer{margin:0;padding:0;}
		.footer p{text-align: center; color:#999; font-weight: 200;margin-top:20px;font-size:12px;}
		a{font-size:14px !important; font-weight: 300;padding:5px 20px;}
		.logo{text-align: center; padding-top:60px;}
		.logo img{width:70px;opacity: 0.8; border-radius: 50%;}
		.amount{font-size:48px; text-align: center; color:#333;}
		.mchname{color:#999;margin:0 20px;border-top:1px solid #eee;padding:12px;font-size:13px;font-weight: 200;}
		.popfeng{position:absolute; bottom:40px;left:0;right:0;background-color:#f8f8f8;line-height: 2px;}
		.popfeng p{color:#bfbfbf;font-size: 12px; text-align: center;width:100%;}
	</style>
	<title>微信支付</title>
</head>
<body class="hide">
<div class="header">
	<div class="logo">
		<img src="<?=$domain?>/img/pay-logo.png">
	</div>
	<div class="amount">￥ <?=$totalFee?></div>
	<div class="mchname">收款说明: <?=$body?></div>
</div>

<div class="footer" style="padding:40px 20px;">
	<a href="javascript:;" class="weui-btn weui-btn_primary" id="payBtn">微信支付</a>
	<a href="javascript:;" class="weui-btn weui-btn_default" id="close" style="background-color: #fff;border-color: #e5e5e5;color:#333;">取消支付操作</a>
	<p>支付完成后, 如需退款请及时联系卖家</p>
	<div class="popfeng">
		<p>由 六久阁 提供支付技术服务</p>
	</div>
</div>

<div id="toast" style="opacity: 0; display: none;">
	<div class="weui-mask_transparent"></div>
	<div class="weui-toast">
		<i class="weui-icon-success-no-circle weui-icon_toast"></i>
		<p class="weui-toast__content">已完成</p>
	</div>
</div>
<script src="https://cdn.bootcss.com/zepto/1.2.0/zepto.min.js"></script>
<script>
	document.addEventListener('touchmove', function(e){e.preventDefault()}, false);

	if (typeof WeixinJSBridge == "undefined"){
		if( document.addEventListener ){
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		}else if (document.attachEvent){
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	}else{
		onBridgeReady();
	}

	function onBridgeReady(){
		WeixinJSBridge.call('hideOptionMenu');
		pay();
	}

	$('#payBtn').on('click', pay);

	$('#close').on('click',function(){
		WeixinJSBridge.call('closeWindow');
	});

	function pay() {
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				"appId": "<?=$jsapi['appId']?>",
				"timeStamp": "<?=$jsapi['timeStamp']?>",
				"nonceStr": "<?=$jsapi['nonceStr']?>",
				"package": "<?=$jsapi['package']?>",
				"signType": "MD5",
				"paySign": "<?=$jsapi['paySign']?>"
			},
			function(res){
				//alert(JSON.stringify(res));
				switch(res.err_msg) {
					case 'get_brand_wcpay_request:cancel':
						//alert('取消支付');
						WeixinJSBridge.call('closeWindow');
						break;
					case 'get_brand_wcpay_request:fail':
						alert('支付失败');
						break;
					case 'get_brand_wcpay_request:ok':
						//alert('支付成功');
						window.location.href='<?=$domain?>/xorpay.php?action=return&out_trade_no=<?php echo $outTradeNo?>&total_fee=<?php echo $totalFee?>';
						break;
					default:
						break;
				}
			}
		);
	}

</script>
</body>
</html>
<?php
	exit();
endif;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>扫码付款</title>
	<meta http-equiv="content-type" content="text/html;charset=<?php echo $cfg_soft_lang; ?>">
	<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
		}
		body {
			background-color: #f9f9f9;
			font-family: Arial, STHeiti, Helvetica, sans-serif;
			font-size: 12px;
			color: #666;
			padding-top: 4px;
		}
		h2 {
			color: #000;
			font-weight: normal;
			font-size: 15px;
			line-height: 2.6em;
			padding: 0 4.6%;
		}
		div.icon {
			width: 50%;
			margin: 1.5em auto;
		}
		div.icon img {
			width: 100%;
		}
		.message {
			text-align: center;
			font-weight: bold;
		}
		.am-button {
			-ms-box-sizing: border-box;
			box-sizing: border-box;
			display: inline-block;
			margin: 0;
			padding: 4px 8px;
			width: 100%;
			text-align: center;
			font-size: 18px;
			line-height: 2;
			border-radius: 4px;
			background-clip: padding-box;
		}
		.result {
			font-weight: 500;
		}
		.result-botton {
			margin: 0 15px 20px;
		}
		.result-botton a {
			display: block;
			margin: auto;
			-webkit-box-sizing: border-box;
			box-sizing: border-box;
			max-width: 384px;
			height:44px;
			text-align: center;
			text-decoration: none;
		}
		.result-botton a.am-button-white {
			color: #333;
			background-color: #fff;
			border: 1px solid #ccc;
		}
		.result-botton a.am-button-green {
			color: #fff;
			background:#00c800;
			border:1px solid #00aaee;
		}
		.result-botton a.am-button-blue {
			color: #fff;
			background:#108ee9;
			border:1px solid #00aaee;
		}
		.result-botton .am-button[disabled=disabled] {
			color: #e6e6e6;
			background: #f8f8f8;
			border: 1px solid #dedede;
		}
		@media (max-width: 767px) {
			#pay-tip{
				width:100%
			}
		}
		#qrDiv{
			width:300px;display: block;margin: auto;border: 1px #ccc solid;height: 300px;background: url('/images/loadinglit.gif') #fff 50% no-repeat;
		}
		#qrDiv img{
			text-align:center;
			padding: 20px;
		}
	</style>
	<script src="https://cdn.bootcss.com/jquery/2.1.0/jquery.min.js" type="text/javascript" charset="<?php echo $cfg_soft_lang; ?>"></script>
	<script src="https://cdn.bootcss.com/jquery.qrcode/1.0/jquery.qrcode.min.js" type="text/javascript" charset="<?php echo $cfg_soft_lang; ?>"></script>
</head>
<body>
<div class="am-content">
	<div id="pay-content" style="display:none">
		<div style="padding: 20px 0 10px;text-align:center;">
			<div style="font-size: 22px;display: block;margin: auto;" id="order_subject"><?php echo $subject?></div>
		</div>
		<div style="padding: 5px 0 5px;text-align:center">						
			<div style="font-size: 14px;display: block;margin: auto;"><span> 付款金额</span> <span style="margin: 2px 2px;color:#f60"> ￥ <?php echo sprintf("%.2f",$total_fee);?></span></div>
		</div>
		<div>
			<div style="position: relative;width: 100%;display: block">									
				<div id="qrDiv"></div>										
			</div>
		</div>
		<div  style="padding: 5px 0 5px;text-align:center">
			<?php
			if(substr($pay_tip,0,4)=='http'){
				$pay_tip = '<img src="'.$pay_tip.'" id="pay-tip"/>';
			}
			?>
			<div id="tips" style="font-size: 12px;display: block;margin: auto;width: 90%;"><?=$pay_tip ? $pay_tip : '使用 微信 扫码完成付款'?></div>
		</div>
<?php
            if($payment['pay_channel']=='支付宝和微信'):
        ?>


		<div class="result"  style="padding: 10px 0 10px;">
			<div class="result-botton"><a class="J-change am-button am-button-white" href="#">选择其他支付方式</a></div>
		</div>
<?php
            endif;
        ?>

	</div>
	<div id="change-content">
		<div style="padding: 20px 0 10px;text-align:center">
			<div style="font-size: 22px;display: block;margin: auto;">请选择支付方式</div>
		</div>
		<div class="pay-types"  style="padding: 10px 0 10px;">
			<div class="result-botton"><a class="J-change-paytype am-button am-button-blue" data-type="alipay" href="#">支付宝</a></div>
			<div class="result-botton"><a class="J-change-paytype am-button am-button-green" data-type="weixin" href="#">微信支付</a></div>
		</div>
		<input type="hidden" id="out_trade_no" value="<?php echo $out_trade_no?>">
	</div>
</div>
<script>
	$.ajaxSetup({ cache: false });
	var t = 0;
	$(".J-change").click(function(){
		clearInterval(t);	
		$("#pay-content").hide();
		$("#change-content").show();
	});

<?php
        if($payment['pay_channel']=='支付宝'):
    ?>
        doPay('alipay');
    <?php
        elseif($payment['pay_channel']=='微信'):
    ?>
        doPay('weixin');
    <?php
        endif;
    ?>


	$(".J-change-paytype").click(function(){
			var me = $(this);
		var type = me.data('type');
        doPay(type);
	});
	
	function doPay(paymode) {
		$("#pay-content").show();
		$("#change-content").hide();
		$("#qrDiv").html('');

		
		var out_trade_no = $("#out_trade_no").val();
		var order_subject = $("#order_subject").text();	
		$("#tips").text('付款二维码获取中...');			
		

			$.getJSON('<?=$domain?>/xorpay.php', {action:'getQrcode',paymode:paymode,out_trade_no:out_trade_no,total_fee:<?php echo $total_fee?>},function (result) {
            var reg = "/"+out_trade_no+"/g";
            $("#order_subject").text(order_subject.replace(eval(reg),result.out_trade_no));
            $("#out_trade_no").val(result.out_trade_no);
            var paytype = paymode=='alipay' ? '支付宝' : '微信';
            if(result.status=='ok'){
                var tip = '<?=$pay_tip ? $pay_tip : "使用 '+paytype+' 扫码完成付款"?>';
                $("#tips").text(tip);
                checkOrder(result.info.qr);
            }else{
                $("#tips").html('<b style="color:red">'+result.status+'</b>');
            }
        });
    }



	function checkOrder(qrurl)
	{
		var out_trade_no = $("#out_trade_no").val();
		t = setInterval(function () {
			var url = "<?=$domain?>/xorpay.php?action=checkorder&out_trade_no="+out_trade_no;
			$.getJSON(url, function (result) {
				//alert(result.code);
				if (result.code == 0) {
					window.location.href = '<?=$domain?>/xorpay.php?action=return&out_trade_no='+out_trade_no+'&total_fee=<?php echo $total_fee?>';
				}
				if (result.code == 2) {
					$("#wait-pay").show();
					$("#tips").text('等待付款');
				}
			});
		}, 2000);
	   
		if(isIE()===false){
			$("#qrDiv").qrcode({
				width: 260, //宽度
				height:260, //高度
				text: qrurl //任意内容
			});
			//获取网页中的canvas对象
			var mycanvas1=document.getElementsByTagName('canvas')[0];
			//将转换后的img标签插入到html中
			var img=convertCanvasToImage(mycanvas1);
			$('#qrDiv').html(img);
		}else{
			var html = '<img src="https://www.kuaizhan.com/common/encode-png?large=true&data='+qrurl+'" style="display: block;margin: auto;"/>';
			$('#qrDiv').html(html);
		}
		
	}

	//从 canvas 提取图片 image
	function convertCanvasToImage(canvas) {
		//新Image对象，可以理解为DOM
		var image = new Image();
		// canvas.toDataURL 返回的是一串Base64编码的URL，当然,浏览器自己肯定支持
		// 指定格式 PNG
		image.src = canvas.toDataURL("image/png");
		return image;
	}
	
	function isIE() {
		var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
		var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
		var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
		var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
		if(isIE || isEdge || isIE11) {
			return true; 
		}else{
			return false;
		}
	}
</script>
</body>
</html>
<?php
function curlPost($url = '', $postData = '', $options = array())
{
    if (is_array($postData)) {
        $postData = http_build_query($postData);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); //设置cURL允许执行的最长秒数
    if (!empty($options)) {
        curl_setopt_array($ch, $options);
    }
    //https请求 不验证证书和host
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
function isMobile() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    if(isWeixin()){
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高。其中'MicroMessenger'是电脑微信
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile','MicroMessenger');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}
function isWeixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    } else {
        return false;
    }
}
function isIE() {
    $userbrowser = $_SERVER['HTTP_USER_AGENT'];
    if ( preg_match( '/MSIE/i', $userbrowser ) ) {
        $usingie = true;
    } else {
        $usingie = false;
    }
    return $usingie;
}